package com.JavaNet.chapter8_client_socket.full_quplex;


import javax.swing.*;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.net.*;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-20
 * <p>
 * 服务器端，全双工
 */

@Deprecated
public class MyServer3 extends JFrame implements ActionListener, KeyListener {

    JTextArea jta = null;
    JTextField jtf = null;
    JButton jb = null;
    JScrollPane jsp = null;

    JPanel jp1 = null;

    //把信息发送给客户端的对象
    PrintWriter pw = null;

    public static void main(String[] args) {

        MyServer3 ms3 = new MyServer3();
    }

    public MyServer3() {
        jta = new JTextArea();
        jsp = new JScrollPane(jta);
        jtf = new JTextField(15);
        jb = new JButton("发送");
        jb.addActionListener(this);

        jp1 = new JPanel();
        jp1.add(jtf);
        jp1.add(jb);
        this.add(jsp, "Center");
        this.add(jp1, "South");
        this.setTitle("QQ聊天-服务器");
        this.setSize(320, 240);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        try {
            //服务器监听
            ServerSocket ss = new ServerSocket(9988);
            //等待客户端连接
            Socket s = ss.accept();

            InputStreamReader isr = new InputStreamReader(s.getInputStream());
            BufferedReader br = new BufferedReader(isr);

            pw = new PrintWriter(s.getOutputStream(), true);

            //读取从客户端发来的消息
            while (true) {
                //读取从客户端发来的消息
                String info = br.readLine();
                jta.append("客户端说：" + info + "\r\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void actionPerformed(ActionEvent arg0) {

        //如果用户按下按发送信的按钮
        if (arg0.getSource() == jb) {
            //把服务器在jtf写的内容发送给客户端
            String info = jtf.getText();

            jta.append("服务器说：" + info + "\r\n");
            pw.print(info);
            //清空输入框内容
            jtf.setText("");
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getSource() == jtf) {
            //System.out.println(e.getKeyCode());
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                String info = jtf.getText();
                jta.append("服务器说：" + info + "\r\n");
                pw.println(info);
                //清空内存
                jtf.setText("");
            }
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {


    }

    @Override
    public void keyReleased(KeyEvent e) {


    }

}
